package com.example.springboot.service.impl;

import com.example.springboot.common.Constants;
import com.example.springboot.common.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Patent;
import com.example.springboot.mapper.PatentMapper;
import com.example.springboot.service.IPatentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.utils.DataBaseSearcher;
import com.example.springboot.utils.JieBaUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
public class PatentServiceImpl extends ServiceImpl<PatentMapper, Patent> implements IPatentService {

    @Resource
    private PatentMapper patentMapper;

    //根据关键词搜索专利，sql搜索
    @Override
    public Result searchByWords(int PageNum, int PageSize, String words) throws IOException {
        Page page = new Page();
        JieBaUtil jieBaUtil = new JieBaUtil();
        List<String> keyWords = jieBaUtil.separateAndClear(words);
        if (keyWords.isEmpty())
            return Result.success("请输入关键词!",null);
        else {
            List<Patent> result = new ArrayList<>();
            for (String keyWord : keyWords) {
                List<Patent> perResult = patentMapper.searchByKeyWord(keyWord);
                result = jieBaUtil.listsToOne(result,perResult);
            }
            Collections.sort(result);
            return Result.success(page.startPage(result,PageNum,PageSize));
        }
    }

    //根据关键词搜索专利,Lucene版
    @Override
    public Result searchByKeyWords(int PageNum, int PageSize, String words) throws IOException {
        JieBaUtil jieBaUtil = new JieBaUtil();
        Page page = new Page();
        List<String> keyWords = jieBaUtil.separateAndClear(words);
        List<Patent> result = new ArrayList<>();
        if (keyWords.isEmpty()) {
            result = DataBaseSearcher.searchData(words,words);
        }
        else {
            for (String keyword : keyWords) {
                List<Patent> perResult = DataBaseSearcher.searchData(keyword,words);
                result = jieBaUtil.listsToOne(result,perResult);
            }
        }
        if(result.isEmpty()) {
            return Result.error(Constants.CODE_600,null);
        }
        Collections.sort(result);
        return Result.success(page.startPage(result,PageNum,PageSize));
    }


}
